package cz.kfad.ofrss.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import cz.kfad.ofrss.R;
import cz.kfad.ofrss.backend.BackendService;
import cz.kfad.ofrss.backend.IBackend;
import cz.kfad.ofrss.common.ApplicationContext;
import cz.kfad.ofrss.common.SimpleGestureFilter;
import cz.kfad.ofrss.common.SimpleGestureFilter.SimpleGestureListener;
import cz.kfad.ofrss.model.RssFeed;

import java.util.ArrayList;
import java.util.List;

public class RssFeedActivity extends SherlockActivity implements SimpleGestureListener {

    public static final String RSS_ID_KEY = "RSS_ID_KEY";
    public static final String RSS_FEED_IDS_KEY = "RSS_FEED_IDS_KEY";
    public static final String RSS_TITLE_KEY = "RSS_TITLE_KEY";

    public static final String RESTORE_ACTUAL_POSITION_KEY = "RESTORE_ACTUAL_POSITION_KEY";
    public static final String RESTORE_FEED_IDS_KEY = "RESTORE_FEED_IDS_KEY";

    private List<Integer> idsToShow;
    private int actualPosition;
    private SimpleGestureFilter detector;

    private IBackend backend = BackendService.createBackend(this);
    private TextView rssText;
    private TextView rssTitle;
    private ImageButton rightButton;
    private ImageButton openButton;
    private ImageButton leftButton;
    private ImageButton openOfflineButton;
    private RssFeed actualFeed;
    private String titleText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rss_feed_detail);

        final Intent intent = getIntent();
        final int rssId = intent.getIntExtra(RSS_ID_KEY, -1);
        int[] ids = intent.getIntArrayExtra(RSS_FEED_IDS_KEY);
        idsToShow = new ArrayList<Integer>(ids.length);
        for (int i = 0; i < ids.length; i++) {
            idsToShow.add(ids[i]);
        }
        titleText = intent.getStringExtra(RSS_TITLE_KEY);
        actualPosition = findActualPosition(rssId);

        rssTitle = (TextView) findViewById(R.id.rss_feed_detail_title);
        rssText = (TextView) findViewById(R.id.rss_feed_detail_text);
        rightButton = (ImageButton) findViewById(R.id.rss_feed_detail_next);
        openButton = (ImageButton) findViewById(R.id.rss_feed_detail_open);
        openOfflineButton = (ImageButton) findViewById(R.id.rss_feed_detail_open_offline);
        leftButton = (ImageButton) findViewById(R.id.rss_feed_detail_previous);

        createButtonHandlers();
        show();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent me) {
        this.detector.onTouchEvent(me);
        return super.dispatchTouchEvent(me);
    }

    @Override
    protected void onResume() {
        super.onResume();
        detector = new SimpleGestureFilter(this, this);
        ApplicationContext appState = ((ApplicationContext) getApplicationContext());
        appState.setContextToAsynTasks(this);
    }

    private void goRight() {
        if (actualPosition < idsToShow.size() - 1) {
            actualPosition++;
            show();
        }
    }

    private void goLeft() {
        if (actualPosition > 0) {
            actualPosition--;
            show();
        }
    }

    private void createButtonHandlers() {
        rightButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                goRight();
            }

        });
        leftButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                goLeft();

            }
        });
        openButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final String url = actualFeed.getUrl();

                final boolean openInBrowser = PreferenceManager.getDefaultSharedPreferences(RssFeedActivity.this).getBoolean("openFeedDetailPref", false);

                if (openInBrowser) {
                    final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(browserIntent);
                } else {
                    final Intent intent = new Intent(RssFeedActivity.this, WebViewActivity.class);
                    intent.putExtra(WebViewActivity.URL, url);
                    startActivity(intent);
                }
            }
        });
        openOfflineButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String content = actualFeed.getContent();
                if (content == null) {
                    Toast.makeText(RssFeedActivity.this, "no data", Toast.LENGTH_SHORT).show();
                    return;
                }
                final Intent intent = new Intent(RssFeedActivity.this, OfflineWebViewActivity.class);
                intent.putExtra(OfflineWebViewActivity.CONTENT, content);
                startActivity(intent);

            }
        });

    }

    private void show() {
        final Integer feedId = idsToShow.get(actualPosition);
        actualFeed = backend.findFeed(feedId);
        backend.setFeedIsRead(feedId);
        final String title = actualFeed.getTitle();
        setTitle(titleText + " (" + (actualPosition + 1) + "/" + idsToShow.size() + ")");
        rssTitle.setText(title);
        rssText.setText(actualFeed.getText());
        checkButtons();
    }

    private void checkButtons() {
        leftButton.setEnabled(actualPosition > 0);
        rightButton.setEnabled(actualPosition < idsToShow.size() - 1);
    }

    private int findActualPosition(int rssId) {
        for (int i = 0; i < idsToShow.size(); i++) {
            if (idsToShow.get(i) == rssId) {
                return i;
            }
        }
        return 0;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(R.string.delete).setIcon(android.R.drawable.ic_menu_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final CharSequence itemTitle = item.getTitle();

        if (getResources().getString(R.string.delete).equals(itemTitle)) {
            backend.deleteFeed(idsToShow.get(actualPosition));
            idsToShow.remove(actualPosition);
            if (actualPosition >= idsToShow.size()) {
                actualPosition--;
            }
            if (actualPosition < 0) {
                Toast.makeText(RssFeedActivity.this, R.string.feed_detail_emptySet, Toast.LENGTH_LONG).show();
                finish();
            } else {
                show();
            }
        } else {
            return false;
        }
        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(RESTORE_ACTUAL_POSITION_KEY, actualPosition);
        int[] idsArray = new int[idsToShow.size()];
        for (int i = 0; i < idsArray.length; i++) {
            idsArray[i] = idsToShow.get(i);
        }
        //tests svn
        outState.putIntArray(RESTORE_FEED_IDS_KEY, idsArray);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        actualPosition = savedInstanceState.getInt(RESTORE_ACTUAL_POSITION_KEY);
        int[] ids = savedInstanceState.getIntArray(RESTORE_FEED_IDS_KEY);
        idsToShow = new ArrayList<Integer>(ids.length);
        for (int i = 0; i < ids.length; i++) {
            idsToShow.add(ids[i]);
        }
        show();
    }

    @Override
    public void onSwipe(int direction) {
        switch (direction) {

            case SimpleGestureFilter.SWIPE_RIGHT:
                goLeft();
                break;
            case SimpleGestureFilter.SWIPE_LEFT:
                goRight();
                break;
            default:

        }
    }

    @Override
    public void onDoubleTap() {

    }
}